package com.xiashitech.agent.instrumentation.spring.controller.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import java.util.Optional;

import static com.xiashitech.agent.instrumentation.spring.controller.XSSpringControllerSingletons.controllerInstrumenter;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class XSSpringControllerMethodInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return named("org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod");
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                isMethod()
                        .and(isPublic()).and(isFinal())
                        .and(named("invokeAndHandle"))
                        .and(takesArgument(0, named("org.springframework.web.context.request.ServletWebRequest"))),
                XSSpringControllerMethodInstrumentation.class.getName() + "$InvokeAndHandleAdvice");
        transformer.applyAdviceToMethod(
                isMethod()
                        .and(isPublic()).and(not(isFinal()))
                        .and(named("invokeAndHandle"))
                        .and(takesArgument(0, named("org.springframework.web.context.request.ServletWebRequest"))),
                XSSpringControllerMethodInstrumentation.class.getName() + "$InvokeAndHandleAdvice");
    }


    public static class InvokeAndHandleAdvice {

        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.This Object servletInvocableHandlerMethod,
                @Advice.Argument(0) Object request,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope,
                @Advice.Local("user") UserRequest userRequest) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringControllerMethodInstrumentation");
            try {
                if(CacheStatus.cannotRun()) {
                    return;
                }
                Optional<UserRequest> userRequestOptional = Java8Bridge.executeRuleForUserInfoMatchRule(request);
                if(userRequestOptional.isPresent()) {
                    userRequest = userRequestOptional.get();
                } else {
                    userRequest = UserRequest.builder().build();
                }
                userRequest.setAdviceObject(servletInvocableHandlerMethod);
                userRequest.setRequest(request);
                Context parentContext = currentContext();
                if (controllerInstrumenter().shouldStart(parentContext,userRequest)) {
                    parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
                    context = controllerInstrumenter().start(parentContext, userRequest);
                    context = BaggageUtil.syncBaggage()
                            .put("xs.userId",userRequest.getUserid() == null ? "" : userRequest.getUserid())
                            .put("xs.loginName",userRequest.getLoginName() == null ? "" : userRequest.getLoginName())
                            .put("xs.sessionId",userRequest.getSessionId() == null ? "" : userRequest.getSessionId())
                            .put("xs.requestDate",userRequest.getRequestDate() == null ? "" : userRequest.getRequestDate().toString())
                            .put("xs.sessionUpdate",userRequest.getSessionUpdate() == null ? "false" : userRequest.getSessionUpdate().toString())
                            .put("endpoint-api",userRequest.getEndpointApi())
                            .put("api-systemId",userRequest.getApiSystemId())
                            .build().storeInContext(context);
                    scope = context.makeCurrent();
                }
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            durationPrinter.printElapseDuration("InvokeAndHandleAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.Argument(0) Object request,
                @Advice.Thrown Throwable throwable,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope,
                @Advice.Local("user") UserRequest userRequest) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringControllerMethodInstrumentation");
            try {
                if (CacheStatus.cannotRun()) {
                    return;
                }
                if (scope == null) {
                    return;
                }
                Object servletInvocableHandlerMethod = userRequest.getAdviceObject();
                if (userRequest.getUserid() == null || "".equals(userRequest.getUserid())) {
                    Optional<UserRequest> userRequestOptional = Java8Bridge.executeRuleForUserInfoMatchRule(request);
                    if (userRequestOptional.isPresent() && userRequestOptional.get().getUserid() != null && !"".equals(userRequestOptional.get().getUserid())) {
                        userRequest = userRequestOptional.get();
                        userRequest.setSessionUpdate(true);
                    }
                }
                scope.close();
                userRequest.setAdviceObject(servletInvocableHandlerMethod);
                userRequest.setRequest(request);
                controllerInstrumenter().end(context, userRequest, null, throwable);
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            durationPrinter.printElapseDuration("InvokeAndHandleAdvice e");
        }
    }
}
